package edu.wayne.cs.csc4110.hw6.framework.gui.login;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import edu.wayne.cs.csc4110.hw6.framework.GameAuthentication;
import edu.wayne.cs.csc4110.hw6.framework.GameCore;
import edu.wayne.cs.csc4110.hw6.framework.gui.lobby.GameButton;
import edu.wayne.cs.csc4110.hw6.framework.lobby.GameLobbyServer;
import edu.wayne.cs.csc4110.hw6.framework.plugin.ActivePlugin;
import edu.wayne.cs.csc4110.hw6.interfaces.Authentication;
import edu.wayne.cs.csc4110.hw6.interfaces.user.User;

public class LoginPanel extends JPanel {

	private JTextField userField;
	private JButton loginBtn;
	private User user = null;

	public LoginPanel(final ActivePlugin plugin, final GameCore core) {
		JPanel contenPane = new JPanel();
		userField = new JTextField(10);
		loginBtn = new GameButton("Login");
		contenPane.add(userField);
		contenPane.add(loginBtn);
		this.add(contenPane);
		loginBtn.addActionListener(new LoginListener(plugin, core));
	}

	private final class LoginListener implements ActionListener {
		private final Authentication auth;
		private ActivePlugin plugin;
		private final GameCore core;

		private LoginListener(ActivePlugin plugin, GameCore core) {
			this.plugin = plugin;
			this.auth = new GameAuthentication(this.plugin);
			this.core = core;

		}

		@Override
		public void actionPerformed(ActionEvent e) {
			String username = userField.getText();
			if (username.equals("")) {
				JOptionPane.showMessageDialog(userField,
						"You cannot enter a empty Username!");
			} else {
				if (!auth.isLoggedIn(username)) {
					user = auth.login(username);
					if (user != null) {
						GameLobbyServer.getInstance().addUser(user);
						core.startPlugin(this.plugin, user);
					}
				} else {
					JOptionPane.showMessageDialog(userField,
							"You are already logged in");
				}
			}

		}
	}
}
